package com.imooc.controller;

import com.imooc.DTO.ProductDTO;
import com.imooc.DTO.ProductInfoDTO;
import com.imooc.DTO.ResultDTO;
import com.imooc.dataobject.ProductCategory;
import com.imooc.dataobject.ProductInfo;
import com.imooc.service.CategoryService;
import com.imooc.service.ProductService;
import com.imooc.util.ResultDTOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultDTO list() {

        // 1.查询所有的上架商品

        List<ProductInfo> productInfoList = productService.findUpAll();

        // 2.一次性查询
        // 传统方法
//        List<Integer> categoryTypeList = new ArrayList<>();
//        for (ProductInfo productInfo: productInfoList) {
//            categoryTypeList.add(productInfo.getCategoryType());
//        }

        // 精简方法
        List<Integer> categoryTypeList =  productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

        // 3.数据拼装

        List<ProductDTO> productDTOList = new ArrayList<>();
        for (ProductCategory productCategory: productCategoryList) {
            ProductDTO productDTO = new ProductDTO();
            productDTO.setCategoryType(productCategory.getCategoryType());
            productDTO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoDTO> productInfoDTOList = new ArrayList<>();

            for(ProductInfo productInfo: productInfoList) {
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                    ProductInfoDTO productInfoDTO = new ProductInfoDTO();
                    BeanUtils.copyProperties(productInfo, productInfoDTO);
                    productInfoDTOList.add(productInfoDTO);
                }
            }

            productDTO.setProductInfoDTOList(productInfoDTOList);
            productDTOList.add(productDTO);

        }

        return ResultDTOUtil.success(productDTOList);
    }

}
